﻿using System;
using System.Runtime.InteropServices;

namespace RxjhServer
{
	public class ClassDllImport
	{
		private static IntPtr instance;

		[DllImport("Kernel32.dll")]
		public static extern IntPtr LoadLibrary(string lpFileName);

		[DllImport("kernel32.dll", SetLastError = true)]
		public static extern int GetProcAddress(IntPtr hModule, string lpProcName);

		[DllImport("kernel32.dll", SetLastError = true)]
		public static extern bool FreeLibrary(IntPtr hModule);

		private static Delegate GetAddress(IntPtr dllModule, string functionname, Type t)
		{
			int procAddress = ClassDllImport.GetProcAddress(ClassDllImport.instance, functionname);
			if (procAddress == 0)
			{
				return null;
			}
			return Marshal.GetDelegateForFunctionPointer(new IntPtr(procAddress), t);
		}

        static public void LoadLib()
        {
            string dllPath = "rxjhDeBuf.dll";
            //dllPath = ConfigurationSettings.AppSettings["dllPath"].ToString();
            instance = LoadLibrary(dllPath);
            if (instance.ToInt32() == 0)
            {
                Form1.WriteLine(1, "rxjhDeBuf.dll不存在");
                //throw new LoadLibraryException("请在App.Config中配置引擎DLL的路径!");
            }
            else
            {
                Form1.WriteLine(2, "登陆器插件加载成功");
            }
        }
        public static void FreeLib()
		{
			ClassDllImport.FreeLibrary(ClassDllImport.instance);
		}

		public static void Decrypta(byte[] lpBuffer, int nDataLength)
		{
			try
			{
				ClassDllImport.Decrypt decrypt = (ClassDllImport.Decrypt)ClassDllImport.GetAddress(ClassDllImport.instance, "Decrypt", typeof(ClassDllImport.Decrypt));
				decrypt(lpBuffer, nDataLength);
			}
			catch (Exception)
			{
				Form1.WriteLine(1, "rxjhDeBuf.dll版本错误");
			}
		}

		public delegate int Decrypt(byte[] lpBuffer, int nDataLength);
	}
}
